using System;
using System.Collections.Generic;
using System.Web.Mvc;
using MvcContrib.Pagination;
using MvcContrib.UI.Grid.Syntax;

namespace etcetera.Mvc.UI.Grid
{
    public static class GridExtensions
    {
        /// <summary>
        /// Creates a grid using the specified datasource.
        /// </summary>
        /// <typeparam name="T">Type of datasouce element</typeparam>
        /// <returns></returns>
        public static IGridEx<T> GridEx<T>(this HtmlHelper helper, IEnumerable<T> dataSource) where T : class
        {
            return new GridEx<T>(dataSource, helper.ViewContext.HttpContext.Response.Output, helper.ViewContext);
        }

        public static IGridEx<T> GridEx<T>(this HtmlHelper helper, string viewDataKey) where T : class
        {
            var dataSource = helper.ViewContext.ViewData.Eval(viewDataKey) as IEnumerable<T>;

            if (dataSource == null)
            {
                throw new InvalidOperationException(string.Format(
                                                        "Item in ViewData with key '{0}' is not an IEnumerable of '{1}'.",
                                                        viewDataKey,
                                                        typeof(T).Name));
            }

            return helper.GridEx(dataSource);
        }
        
        public static IGridEx<T> WithTitle<T>(this IGridEx<T> grid, string title) where T : class
        {
            return grid.WithTitle(title);
        }

        public static CustomPagination<T> AsCustomPagination<T>(this ICollection<T> collection, int pageNumber, int pageSize, int totalItems) where T: class
        {
            return new CustomPagination<T>(collection, pageNumber, pageSize, totalItems);
        }
    }
}